package DAO;

import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import Beans.Company;
import Beans.Courier;
import Beans.Express;
import Beans.LeftPackage;
import Beans.Package;
import Beans.Terminal;
import Utils.CalculateDate;
import Utils.HibernateUtil;
import Utils.PageBean;
import Utils.QueryPackage;

public class PackageDao {

	private SessionFactory sessionFactory;
	Transaction tr = null;

	public PackageDao() {
		sessionFactory = HibernateUtil.getSessionFactory();
	}

	CourierDao courierDao = new CourierDao();
	Courier courier = null;

	/**
	 * 
	 * @param phoneNum
	 *            手机号码
	 * @return 历史包裹信息
	 */

	@SuppressWarnings("unchecked")
	public ArrayList<Package> getHistoryPackageByPhone(String phoneNum) {

		Session session = sessionFactory.openSession();
		ArrayList<Package> packages = null;

		tr = session.beginTransaction();

		Criteria c = session.createCriteria(Package.class);
		c.add(Restrictions.eq("userPhone", phoneNum));
		c.add(Restrictions.eq("packageStatus", 1));
		c.addOrder(Order.desc("storeTime"));
		packages = (ArrayList<Package>) c.list();

		tr.commit();
		session.close();
		return packages;

	}

	/**
	 * 根据手机号返回包裹信息 set package status to be taken
	 * 
	 * @param phoneNum
	 *            手机号码
	 * @return 用户在系统中记录的所有包裹信息
	 */

	@SuppressWarnings("unchecked")
	public ArrayList<Package> getPackageDetailByPhone(String phoneNum) {

		Session session = sessionFactory.openSession();
		ArrayList<Package> packages = null;

		tr = session.beginTransaction();

		Criteria c = session.createCriteria(Package.class);

		c.add(Restrictions.like("userPhone", "%" + phoneNum + "%"));

		c.addOrder(Order.asc("userPhone"));
		c.addOrder(Order.desc("getTime"));
		packages = (ArrayList<Package>) c.list();

		tr.commit();
		session.close();
		return packages;

	}

	/**
	 * 查询快递员包裹
	 * 
	 * @param phoneNum
	 * @return
	 */
	public ArrayList<Package> getByCourierPhone(String phoneNum) {

		Session session = sessionFactory.openSession();
		ArrayList<Package> packages = null;
		courier = courierDao.getByMobileNum(new BigInteger(phoneNum));
		tr = session.beginTransaction();

		Criteria c = session.createCriteria(Package.class);

		c.add(Restrictions.eq("courier", courier));

		c.addOrder(Order.desc("getTime"));
		packages = (ArrayList<Package>) c.list();

		tr.commit();
		session.close();
		return packages;

	}
	
	public ArrayList<Package> getByAgent(List<Terminal> terminals,Timestamp starttime,Timestamp endTime) {
		
		Session session = sessionFactory.openSession();
		ArrayList<Package> packages = null;
		tr = session.beginTransaction();
		Criteria c = session.createCriteria(Package.class);
		c.add(Restrictions.in("terminal", terminals));
		c.add(Restrictions.between("storeTime", starttime, endTime));
		
		c.addOrder(Order.asc("userPhone"));
		c.addOrder(Order.desc("storeTime"));
		packages = (ArrayList<Package>) c.list();
		
		tr.commit();
		session.close();
		return packages;
		
	}

	/**
	 * 查询快递公司包裹
	 * 
	 * @param phoneNum
	 * @return
	 */
	public ArrayList<Package> getByCompany(String companyName) {

		Session session = sessionFactory.openSession();
		ArrayList<Package> packages = null;
		tr = session.beginTransaction();

		Criteria c = session.createCriteria(Package.class);

		c.add(Restrictions.eq("belong", companyName));

		c.addOrder(Order.desc("getTime"));
		packages = (ArrayList<Package>) c.list();

		tr.commit();
		session.close();
		return packages;

	}

	public ArrayList<Package> getByCourierRfid(String rfid) {

		Session session = sessionFactory.openSession();
		ArrayList<Package> packages = null;
		courier = courierDao.getByCourierRfid(rfid);
		tr = session.beginTransaction();

		Criteria c = session.createCriteria(Package.class);

		c.add(Restrictions.eq("courier", courier));

		c.addOrder(Order.desc("getTime"));
		packages = (ArrayList<Package>) c.list();

		tr.commit();
		session.close();
		return packages;

	}

	public ArrayList<Package> getReturnPackages() {

		Session session = sessionFactory.openSession();
		ArrayList<Package> packages = null;

		tr = session.beginTransaction();

		Criteria c = session.createCriteria(Package.class);

		Object[] status = { 2, 4 };
		c.add(Restrictions.in("packageStatus", status));

		c.addOrder(Order.asc("packageStatus"));
		packages = (ArrayList<Package>) c.list();

		tr.commit();
		session.close();
		return packages;

	}

	public ArrayList<Package> getDealedPackages() {

		Session session = sessionFactory.openSession();
		ArrayList<Package> packages = null;

		tr = session.beginTransaction();

		Criteria c = session.createCriteria(Package.class);

		c.add(Restrictions.eq("packageStatus", 5));

		c.addOrder(Order.desc("getTime"));
		c.addOrder(Order.asc("packageStatus"));
		packages = (ArrayList<Package>) c.list();

		tr.commit();
		session.close();
		return packages;

	}
	/**
	 * 获取快递员存件情况
	 * @return
	 */
	public ArrayList<Package> getCourierStore(int courierID) {
		courier = courierDao.getCourierById(courierID);
		Session session = sessionFactory.openSession();
		ArrayList<Package> packages = null;
		tr = session.beginTransaction();
		Criteria c = session.createCriteria(Package.class);
		c.add(Restrictions.eq("courier", courier));
		c.addOrder(Order.desc("storeTime"));
		packages = (ArrayList<Package>) c.list();
		tr.commit();
		session.close();
		return packages;
		
	}

	public ArrayList<Package> dealPackage(int packageId) {

		Session session = sessionFactory.openSession();

		tr = session.beginTransaction();
		Package p = (Package) session.get(Package.class, packageId);
		p.setPackageStatus(5);
		p.setGetTime(new Timestamp(new Date().getTime()));
		tr.commit();
		session.close();
		return getReturnPackages();

	}

	public void signPackage(int packageId) {

		Session session = sessionFactory.openSession();

		tr = session.beginTransaction();
		Package p = (Package) session.get(Package.class, packageId);
		p.setPackageStatus(2);
		tr.commit();
		session.close();

	}

	public void unLockPackage(int packageId) {

		Session session = sessionFactory.openSession();

		tr = session.beginTransaction();
		Package p = (Package) session.get(Package.class, packageId);
		p.setPackageStatus(0);
		p.setGetTime(null);
		tr.commit();
		session.close();

	}

	/**
	 * 获取该手机号码未取的包裹
	 */

	@SuppressWarnings("unchecked")
	public List<Package> getUnTakenPackageDetailByPhone(String phoneNum) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		Criteria c = session.createCriteria(Package.class);
		c.add(Restrictions.eq("userPhone", phoneNum));
		c.add(Restrictions.eq("packageStatus", 0));
		c.addOrder(Order.desc("storeTime"));
		List<Package> packages = c.list();
		tr.commit();
		session.close();
		return packages;
	}

	/**
	 * 
	 * 根据快递单号返回相应包裹（精确查询） 微信使用
	 * 
	 * 
	 * @param parcelID
	 *            快递单号
	 * @return 快递包裹信息的集合
	 */

	@SuppressWarnings("unchecked")
	public ArrayList<Package> getPackageByParcelID(String parcelID) {

		Session session = sessionFactory.openSession();
		ArrayList<Package> packages = null;
		tr = session.beginTransaction();

		Criteria c = session.createCriteria(Package.class);
		c.add(Restrictions.eq("parcelId", parcelID));
		c.addOrder(Order.asc("getTime"));
		packages = (ArrayList<Package>) c.list();

		tr.commit();
		session.close();
		return packages;

	}

	/**
	 * 根据快递单号返回相应包裹（模糊查询）
	 * 
	 * @param parcelID
	 *            快递单号
	 * @return 快递包裹信息的集合
	 */

	@SuppressWarnings("unchecked")
	public ArrayList<Package> getPackageDetailByParcelID(String parcelID) {

		Session session = sessionFactory.openSession();
		ArrayList<Package> packages = null;
		tr = session.beginTransaction();

		Criteria c = session.createCriteria(Package.class);

		c.add(Restrictions.like("parcelId", "%" + parcelID + "%"));

		c.addOrder(Order.asc("getTime"));
		packages = (ArrayList<Package>) c.list();

		tr.commit();
		session.close();
		return packages;

	}

	/**
	 * 修改包裹状态位为已取
	 * 
	 * @param terminalID
	 * @param boxID
	 * @return
	 */

	@SuppressWarnings("unchecked")
	public Package setPackageTaken(int terminalID, int boxID) {

		TerminalDao terminalDao = new TerminalDao();

		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		List<Package> packages = null;
		Object[] status = { 0, 2 };

		Criteria c = session.createCriteria(Package.class);
		c.add(Restrictions.eq("terminal",
				terminalDao.getTerminalById(terminalID)));
		c.add(Restrictions.eq("boxId", boxID));
		c.add(Restrictions.in("packageStatus", status));
		packages = (ArrayList<Package>) c.list();
		if (packages.iterator().hasNext()) {
			Package p = null;
			for (Package p1 : packages) {
				p1.setGetTime(new Timestamp(new Date().getTime()));
				p1.setPackageStatus(5);// 远程开锁设置为已处理
				session.update(p1);
				p = p1;
			}
			tr.commit();
			session.close();
			return p;
		} else {
			session.close();
			return null;
		}

	}

	public boolean setPackageBack(int terminalID, int boxID) {

		TerminalDao terminalDao = new TerminalDao();

		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		List<Package> packages = null;

		Criteria c = session.createCriteria(Package.class);
		c.add(Restrictions.eq("terminal",
				terminalDao.getTerminalById(terminalID)));
		c.add(Restrictions.eq("boxId", boxID));
		c.add(Restrictions.eq("packageStatus", 4));
		packages = (ArrayList<Package>) c.list();
		if (packages.iterator().hasNext()) {
			for (Package p1 : packages) {
				p1.setPackageStatus(5);
				session.update(p1);
			}
			tr.commit();
			session.close();
			return true;
		} else {
			session.close();
			return false;
		}

	}

	/**
	 * 修改包裹状态位为未取
	 * 
	 * @param terminalId
	 * @param boxId
	 * @return
	 */

	@SuppressWarnings("unchecked")
	public Package setPackageUnTaken(int terminalId, int boxId) {

		TerminalDao terminalDao = new TerminalDao();

		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		List<Package> packages = null;
		Object[] status = { 1, 5 };
		Criteria c = session.createCriteria(Package.class);
		c.add(Restrictions.eq("terminal",
				terminalDao.getTerminalById(terminalId)));
		c.add(Restrictions.eq("boxId", boxId));
		c.add(Restrictions.in("packageStatus", status));
		c.addOrder(Order.desc("storeTime"));
		packages = (ArrayList<Package>) c.list();
		if (packages.iterator().hasNext()) {
			Package p = packages.iterator().next();
			p.setPackageStatus(0);
			p.setGetTime(null);
			p.setFlag(3);
			session.update(p);
			tr.commit();
			session.close();
			return p;
		} else {
			tr.commit();
			session.close();
			return null;
		}
	}

	/**
	 * 返回改终端上的所有包裹
	 * 
	 * @param terminalId
	 * @return
	 */

	@SuppressWarnings("unchecked")
	public List<Package> PackagesInThisTerminal(int terminalId) {

		TerminalDao terminalDao = new TerminalDao();
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		List<Package> packages = null;

		Criteria c = session.createCriteria(Package.class);
		c.add(Restrictions.eq("terminal",
				terminalDao.getTerminalById(terminalId)));
		packages = (ArrayList<Package>) c.list();

		tr.commit();

		session.close();

		return packages;

	}

	/**
	 * 通过包裹Id返回包裹细节
	 * 
	 * @param packageId
	 * @return
	 */
	public Package getPackageDetailsByID(int packageId) {

		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		Package p = null;
		p = (Package) session.get(Package.class, packageId);
		session.getTransaction().commit();
		session.close();
		// p.print();
		return p;

	}

	/**
	 * 修改包裹状态
	 * 
	 * @param packageId
	 * @param status
	 * @return
	 */
	public Package editPackage(int packageId, int status) {

		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		Package p = null;
		p = (Package) session.get(Package.class, packageId);
		p.setPackageStatus(status);
		session.getTransaction().commit();
		session.close();
		// p.print();
		return p;

	}

	public Package editPackage(Package p) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		session.update(p);
		tr.commit();
		session.close();
		return p;

	}

	/**
	 * 根据终端，滞留天数放回滞留包裹
	 * 
	 * @param terminalId
	 *            终端
	 * @param day
	 *            滞留天数
	 * @return 滞留包裹信息列表
	 */

	@SuppressWarnings("unchecked")
	public int getUnTakenPackage(int terminalId, int day) {
		TerminalDao terminalDao = new TerminalDao();
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		List<Package> packages = null;
		Criteria c = session.createCriteria(Package.class);
		c.add(Restrictions.le("storeTime", new Date(new Date().getTime() - 1000
				* 60 * 60 * 24 * day))); // return 3 days untaken parcel
		c.add(Restrictions.isNull("getTime"));
		c.add(Restrictions.eq("packageStatus", 0));
		c.add(Restrictions.eq("terminal",
				terminalDao.getTerminalById(terminalId)));
		packages = (ArrayList<Package>) c.list();
		tr.commit();
		session.close();

		return packages.size();
	}

	/**
	 * 今日包裹信息
	 * 
	 */

	@SuppressWarnings({ "deprecation", "unchecked" })
	public List<Package> getPackagesToday() {
		Date date = new Date();

		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		List<Package> packages = null;
		Criteria c = session.createCriteria(Package.class);

		c.add(Restrictions.ge("storeTime",
				new Date(date.getYear(), date.getMonth(), date.getDate())));

		c.addOrder(Order.asc("terminal"));
		packages = (ArrayList<Package>) c.list();
		tr.commit();
		session.close();

		return packages;
	}

	/**
	 * 剩余包裹查询
	 * 
	 * @param terminalId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Package> getUnTakenPackage(int terminalId) {

		TerminalDao terminalDao = new TerminalDao();
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		List<Package> packages = null;
		Object[] status = { 0, 2, 4 };
		Criteria c = session.createCriteria(Package.class);
		// c.add(Restrictions.le("storeTime", new Date(new Date().getTime() -
		// 1000
		// * 60 * 60 * 24 * day))); // return 3 days untaken parcel
		// c.add(Restrictions.isNull("getTime"));
		// if (company != null) {
		// System.out.println("courierCorp: -------------------------"
		// + company);
		// c.add(Restrictions.like("courierCorp", company, MatchMode.ANYWHERE));
		// }
		c.add(Restrictions.in("packageStatus", status));
		// c.add(Restrictions.or(Restrictions.eq("packageStatus", 0),
		// Restrictions.eq("packageStatus", 4)));
		c.add(Restrictions.eq("terminal",
				terminalDao.getTerminalById(terminalId)));
		c.addOrder(Order.asc("storeTime"));
		packages = (ArrayList<Package>) c.list();

		tr.commit();
		session.close();

		return packages;
	}

	/**
	 * 查看指定终端指定柜号中的未取包裹信息
	 * 
	 * @param terminalId
	 *            终端号
	 * @param boxNum
	 *            柜号
	 * @return 未取包裹信息
	 */

	@SuppressWarnings("unchecked")
	public List<Package> getPacakgeDetailsByBoxNum(int terminalId, int boxNum) {
		TerminalDao terminalDao = new TerminalDao();
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		List<Package> packages = null;
		Object[] status = { 0, 2 };
		Criteria c = session.createCriteria(Package.class);
		c.add(Restrictions.eq("boxId", boxNum));
		c.add(Restrictions.eq("terminal",
				terminalDao.getTerminalById(terminalId)));
		c.add(Restrictions.in("packageStatus", status));
		packages = (ArrayList<Package>) c.list();
		tr.commit();
		session.close();
		return packages;
	}

	public List<Package> getReturnPacakgeDetailsByBoxNum(int terminalId,
			int boxNum) {
		TerminalDao terminalDao = new TerminalDao();
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		List<Package> packages = null;
		Criteria c = session.createCriteria(Package.class);
		c.add(Restrictions.eq("boxId", boxNum));
		c.add(Restrictions.eq("terminal",
				terminalDao.getTerminalById(terminalId)));
		c.add(Restrictions.eq("packageStatus", 4));
		packages = (ArrayList<Package>) c.list();
		tr.commit();
		session.close();
		return packages;
	}

	/**
	 * 查看指定终端指定柜号中的未取包裹信息
	 * 
	 */

	@SuppressWarnings("unchecked")
	public int getPackagesInThisBox(int terminalId, int boxNum) {
		TerminalDao terminalDao = new TerminalDao();
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		List<Package> packages = null;
		Criteria c = session.createCriteria(Package.class);
		c.add(Restrictions.eq("boxId", boxNum));
		c.add(Restrictions.eq("terminal",
				terminalDao.getTerminalById(terminalId)));
		packages = (ArrayList<Package>) c.list();
		tr.commit();
		session.close();
		return packages.size();
	}

	@SuppressWarnings("unchecked")
	public ArrayList<Package> getTerminalUseBetweenPeriod(Date beginTime,
			Date endTime) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		ArrayList<Package> packages = null;
		Criteria c = session.createCriteria(Package.class);
		c.add(Restrictions.ge("storeTime", beginTime));
		c.add(Restrictions.le("storeTime", endTime));
		packages = (ArrayList<Package>) c.list();
		tr.commit();
		session.close();
		return packages;
	}

	@SuppressWarnings("unchecked")
	public ArrayList<Package> getUnTakenPackagesDetailBetweenPeriod(
			int terminalId, Date beginTime, Date endTime) {

		TerminalDao terminalDao = new TerminalDao();
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		ArrayList<Package> packages = null;
		Criteria c = session.createCriteria(Package.class);
		c.add(Restrictions.ge("storeTime", beginTime));
		c.add(Restrictions.le("storeTime", endTime));
		c.add(Restrictions.eq("packageStatus", 0));
		c.add(Restrictions.eq("terminal",
				terminalDao.getTerminalById(terminalId)));
		c.addOrder(Order.asc("boxId"));
		packages = (ArrayList<Package>) c.list();
		tr.commit();
		session.close();

		return packages;
	}

	/**
	 * 根据快递单号返回相应包裹
	 * 
	 * @param parcelId
	 *            快递单号
	 * @return 快递包裹信息的集合
	 */

	@SuppressWarnings("unchecked")
	public ArrayList<Package> getPackageDetailByUser(String parcelId) {

		Session session = sessionFactory.openSession();
		ArrayList<Package> packages = null;
		tr = session.beginTransaction();

		Criteria c = session.createCriteria(Package.class);
		c.add(Restrictions.eq("parcelId", parcelId));
		packages = (ArrayList<Package>) c.list();

		tr.commit();
		session.close();
		return packages;

	}

	@SuppressWarnings("unchecked")
	public int getAllSavedPackage(int terminalId) {
		TerminalDao terminalDao = new TerminalDao();
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		ArrayList<Package> packages = null;
		Criteria c = session.createCriteria(Package.class);
		c.add(Restrictions.eq("terminal",
				terminalDao.getTerminalById(terminalId)));
		packages = (ArrayList<Package>) c.list();
		tr.commit();
		session.close();
		return packages.size();
	}

	@SuppressWarnings("unchecked")
	public int getAllTakePackage(int terminalId) {
		TerminalDao terminalDao = new TerminalDao();
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		ArrayList<Package> packages = null;
		Criteria c = session.createCriteria(Package.class);
		c.add(Restrictions.eq("packageStatus", 1));
		c.add(Restrictions.eq("terminal",
				terminalDao.getTerminalById(terminalId)));
		packages = (ArrayList<Package>) c.list();
		tr.commit();
		session.close();
		return packages.size();
	}

	/**
	 * 返回该网点上的所有包裹
	 * 
	 * @param terminalId
	 * @return
	 */
	public List<LeftPackage> PackagesInThisBranch(int branchId) {

		TerminalDao terminalDao = new TerminalDao();
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		List<LeftPackage> leftPackages = new ArrayList<LeftPackage>();
		List<Terminal> terminals = null;
		terminals = terminalDao.returnTermialByBranchID(branchId);
		for (Terminal t : terminals) {
			LeftPackage leftPackage = new LeftPackage();
			leftPackage.setBranch(t.getBranch().getBranchName());
			leftPackage.setTerminal(t.getName());
			leftPackage.setSaveConst(getAllSavedPackage(t.getTerminalId()));
			leftPackage.setTakeConst(getAllTakePackage(t.getTerminalId()));
			leftPackage.setLeftOneDay(getUnTakenPackage(t.getTerminalId(), 1));
			leftPackage.setLeftTwoDay(getUnTakenPackage(t.getTerminalId(), 2));
			leftPackage.setLeftOverTwoDay(getUnTakenPackage(t.getTerminalId(),
					3));
			leftPackages.add(leftPackage);
		}
		session.close();
		return leftPackages;
	}

	/**
	 * 分页查看某个网点下所有的包裹
	 * 
	 * @param branchId
	 * @return
	 */
	public PageBean<Package> getPackage(int curpage, int pageSize,
			QueryPackage querypage, Object... obj) {
		StringBuffer buff = new StringBuffer();
		StringBuffer bf = new StringBuffer();
		// List<PackageInfo> listpackageInfo=packageInfoDao.getAllPackageInfo();
		if (querypage != null) {
			// select * from package p where p.package_status=0 and
			// package_belong='中通快递' and p.package_box_id=2 or
			// p.package_box_id=3;
			// 模糊查询
			if (querypage.getTerm() != null) {
				buff.append(" and ( p.terminal.name like '%"
						+ querypage.getTerm() + "%'");
				buff.append(" or p.boxId like '%" + querypage.getTerm() + "%'");
				buff.append(" or p.userPhone like '%" + querypage.getTerm()
						+ "%'");
				buff.append(" or p.checkCode like '%" + querypage.getTerm()
						+ "%'");
				buff.append(" or p.storeTime like '%" + querypage.getTerm()
						+ "%')");
			}
			if (querypage.getStrExpBranch() != null) {
				buff.append(" and p.courier.express.expressId="
						+ Integer.parseInt(querypage.getStrExpBranch()));
			}
			if (querypage.getStrCompany() != null) {
				buff.append("and p.courier.express.company.companyId="
						+ Integer.parseInt(querypage.getStrCompany()));
			}
			// 终端
			if (querypage.getTerminal() != null) {
				if (querypage.getTerminal().size() > 0) {
					for (int i = 0; i < querypage.getTerminal().size(); i++) {
						if (i == 0) {
							if (querypage.getTerminal().size() > 1)
								buff.append(" and (");
							else
								buff.append(" and ");
							buff.append(" p.terminal.terminalId="
									+ querypage.getTerminal().get(i));
						} else {
							buff.append("or p.terminal.terminalId="
									+ querypage.getTerminal().get(i));
						}
					}
					if (querypage.getTerminal().size() > 1) {
						buff.append(" )");
					}
				}
			}
			// 包裹状态
			if (querypage.getStatus() != null) {
				if (querypage.getStatus().size() > 0) {
					for (int i = 0; i < querypage.getStatus().size(); i++) {
						if (i == 0) {
							if (querypage.getStatus().size() > 1)
								buff.append(" and (");
							else
								buff.append(" and ");
							buff.append(" p.packageStatus="
									+ querypage.getStatus().get(i));
						} else {
							buff.append("or p.packageStatus="
									+ querypage.getStatus().get(i));
						}
					}
					if (querypage.getStatus().size() > 1) {
						buff.append(" )");
					}
				}
			} else {
				buff.append(" and p.packageStatus=0 ");
			}
			// 存入时间
			if (querypage.getDeposit() != null) {
				buff.append(" and p.storeTime between '"
						+ querypage.getDeposit() + "' and '"
						+ querypage.getEndtime() + "' ");

			} else {
				buff.append(" and timestampdiff(DAY,p.storeTime,now())<=2 ");
			}

			if (querypage.getGetTimeOfstart() != null
					&& querypage.getGetTimeOfend() != null) {
				if (querypage.getGetTimeOfstart() != null) {
					buff.append(" and p.getTime between '"
							+ querypage.getGetTimeOfstart() + "' and '"
							+ querypage.getGetTimeOfend() + "' ");
				}
			}
			// 排序
			if (querypage.getSort() != null) {
				bf.append(" order by " + querypage.getSort());
			} else
				bf.append(" order by p.storeTime desc");
		} else {
			// 排序
			buff.append(" and p.packageStatus=0 ");
			buff.append(" and timestampdiff(DAY,p.storeTime,now())<=2");
			bf.append(" order by p.storeTime desc");
		}

		String hql = "select p from Package p where p.terminal.branch.branchId=?  "
				+ buff.toString() + bf.toString();
		Session session = sessionFactory.openSession();
		Query query = session.createQuery(hql);
		bindParams(query, obj);
		query.setFirstResult((curpage - 1) * pageSize);
		query.setMaxResults(pageSize);
		@SuppressWarnings("unchecked")
		List<Package> list = query.list();
		for (int i = 0; i < list.size(); i++) {
			Package pack = list.get(i);
			if (pack.getGetTime() != null)
				pack.leftTime = CalculateDate.canageDHMS(pack.getGetTime()
						.getTime() - pack.getStoreTime().getTime());
			else
				pack.leftTime = CalculateDate.canageDHMS(new Date().getTime()
						- pack.getStoreTime().getTime());
		}
		String hql1 = "select count(p) from Package p where p.terminal.branch.branchId=?  "
				+ buff.toString();
		Query query1 = session.createQuery(hql1);
		bindParams(query1, obj);
		Object count = query1.uniqueResult();
		session.close();
		PageBean<Package> page = new PageBean<Package>(curpage, pageSize,
				Integer.parseInt(count.toString()), list);
		return page;
	}

	/**
	 * 参数绑定
	 * 
	 * @param query
	 *            查询对象
	 * @param obj
	 *            参数集合
	 */
	private void bindParams(Query query, Object... obj) {
		if (obj != null) {
			for (int i = 0; i < obj.length; i++) {
				query.setParameter(i, obj[i]);
			}
		}
	}

	/**
	 * 查询某个网点下所有终端
	 * 
	 * @param branchId
	 * @return
	 */
	public List<Terminal> getAllTerminalOfBranchId(Integer branchId) {
		String hql = "from Terminal t where t.branch.branchId=?";
		Session session = sessionFactory.openSession();
		Query query = session.createQuery(hql);
		query.setParameter(0, branchId);

		@SuppressWarnings("unchecked")
		List<Terminal> list = query.list();
		session.close();
		return list;
	}

	/**
	 * 查询某个网点下所有快递网点
	 * 
	 * @param branchId
	 * @return
	 */
	public List<Express> getAllExpressOfBranchId(Integer branchId) {
		String hql = "select distinct p.courier.express  from Package p where  p.terminal.branch.branchId=? ";
		Session session = sessionFactory.openSession();
		Query query = session.createQuery(hql);
		query.setParameter(0, branchId);

		@SuppressWarnings("unchecked")
		List<Express> list = query.list();
		session.close();
		return list;
	}

	/**
	 * 查询某个网点下所有快递公司
	 * 
	 * @param branchId
	 * @return
	 */
	public List<Company> getAllCompanyOfBranchId(Integer branchId) {
		String hql = "select distinct p.courier.express.company  from Package p where  p.terminal.branch.branchId=? ";
		Session session = sessionFactory.openSession();
		Query query = session.createQuery(hql);
		query.setParameter(0, branchId);

		@SuppressWarnings("unchecked")
		List<Company> list = query.list();
		session.close();
		return list;
	}

	public static void main(String[] args) {
		QueryPackage querypage = new QueryPackage();
		// querypage.setStrExpBranch("1");
		// System.out.println(new PackageDao().getPackage(1, 2,
		// querypage,1).getList().get(0).getParcelId());

		System.out.println(new PackageDao().getAllCompanyOfBranchId(3).get(0)
				.getCompanyName());
	}

}